import * as sjuRequest from '@/common/sju.request.js'
import * as nav from '@/common/sju.nav.js'
import * as jsAlert from '@/common/sju.alert.js'
import * as login from '@/common/sju.login.js'
// 默认配置
import { t } from '@/common/sju.i18n.js'

// 支付状态常量
const PAY_STATUS = {
  SUCCESS: 'get_brand_wcpay_request:ok',
  CANCEL: 'get_brand_wcpay_request:cancel'
}

/**
 * 微信H5支付
 * @param {object} wxJsApiParam 微信支付参数
 * @param {string} orderCodePay 订单编号
 * @returns {Promise<void>}
 */
function payWeixinH5(wxJsApiParam, orderCodePay) {
  return new Promise((resolve, reject) => {
    const handlePaymentResult = res => {
      if (res.err_msg === PAY_STATUS.SUCCESS) {
        sjuRequest.request('/api/xxx/xxx', 'post', { orderCodePay })
          .then(() => {
            nav.navigateBack(1)
            resolve()
          })
          .catch(reject)
      } else if (res.err_msg === PAY_STATUS.CANCEL) {
        jsAlert.showInfo(t('common.pay.cancel'))
        reject(new Error(t('common.pay.user_cancel')))
      } else {
        jsAlert.showError(t('common.pay.fail_retry'))
        reject(new Error(t('common.pay.fail')))
      }
    }

    const initPayment = () => {
      WeixinJSBridge.invoke(
        'getBrandWCPayRequest',
        {
          appId: wxJsApiParam.appId,
          nonceStr: wxJsApiParam.nonceStr,
          package: wxJsApiParam.package,
          paySign: wxJsApiParam.paySign,
          signType: wxJsApiParam.signType,
          timeStamp: wxJsApiParam.timeStamp
        },
        handlePaymentResult
      )
    }

    if (typeof WeixinJSBridge === 'undefined') {
      const eventMethod = document.addEventListener ? 'addEventListener' : 'attachEvent'
      document[eventMethod]('WeixinJSBridgeReady', initPayment)
    } else {
      initPayment()
    }
  })
}

/**
 * 微信小程序支付
 * @param {string} orderCodePay 订单编号
 * @returns {Promise<void>}
 */
function payWeiXinApp(orderCodePay) {
  return new Promise((resolve, reject) => {
    uni.getProvider({
      service: 'payment',
      success: async res => {
        try {
          const openID = login.getValue('openID')
          if (!openID) {
            await login.weixinLogin()
            return payWeiXinApp(orderCodePay)
          }

          const payRes = await sjuRequest.request(
            '/api/xxx/weixinPay',
            'post',
            { openID, orderCodePay }
          )
          
          const order = JSON.parse(payRes.data.orderInfo)
          uni.requestPayment({
            provider: res.provider,
            orderInfo: payRes.data.orderInfo,
            ...order,
            success: async () => {
              await sjuRequest.request(
                '/api/xxx/weixinPaySuccess',
                'post',
                { orderCodePay }
              )
              resolve()
            },
            fail: err => {
              jsAlert.showError(t('common.pay.fail'))
              reject(err)
            }
          })
        } catch (error) {
          reject(error)
        }
      },
      fail: err => {
        jsAlert.showError(t('common.pay.get_service_fail'))
        reject(err)
      }
    })
  })
}

export {
  payWeixinH5,
  payWeiXinApp
}
